<template>
     <div class="app-container">
  <div class="head-container">
    <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="85px" >
        <el-row :gutter="10" class="flex flex1">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" >
          <el-form-item label="发货日期">
            <div class="flex flex-row">
              <el-date-picker
                v-model="query.sendStartDate"
                align="right"
                unlink-panels
                class="fl1"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                range-separator=""
                placeholder="开始日期"
              />
              <el-date-picker
                v-model="query.sendEndDate"
                align="right"
                unlink-panels
                class="fl1"
                format="yyyy - MM - dd "
                value-format="yyyy-MM-dd"
                default-value
                range-separator=""
                placeholder="结束日期"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单号">
              <el-input v-model="query.code" clearable placeholder="请输入单号" />
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
              <el-form-item label="客户名称">
                <table-select
                  :tableColumns="
                  [
                  {prop:'code',label:'客户编码',width: '100'},
                  {prop:'name',label:'客户名称',width: '150'},
                  {prop:'address',label:'地址'},
                  {prop:'sCustomerName',label:'二批'},
                  ]"
                  labelKey="name"
                  valueKey="id"
                  width="700"
                  :value.sync="query.customerIds"
                  placeholder="请选择客户"
                  url="api/dropDown/basCustomerList"
                ></table-select>
              </el-form-item>
          </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
        <el-form-item label="客户区域">
              <treeselect
                v-model="query.customerAreaIds"
                :options="areaList"
                placeholder="客户区域"
                :normalizer="normalizer"
                multiple
                @input="val=>getNoStr(val,'areaList','customerAreaIds')"
              />
        </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户分类">
                <treeselect
                v-model="query.customerTypeIds"
                :options="typeList"
                placeholder="客户分类"
                :normalizer="normalizer"
                multiple
                @input="val=>getNoStr(val,'typeList','customerTypeIds')"/>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="二批">
            <!--                <zSelect multiple :value.sync="customerIds"  url="api/dropDown/basCustomerList"-->
            <!--                         style="width:  100%;"/>-->
            <table-select
              :tableColumns="
                [
                {prop:'code',label:'二批编码',width: '100'},
                {prop:'name',label:'二批名称',width: '150'},
                ]"
              labelKey="name"
              valueKey="id"
              width="400"
              :params="{type:3}"
              :value.sync="query.sCustomerIds"
              placeholder="请选择二批"
              url="api/dropDown/basCustomerList"
            ></table-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="业务员">
                <table-select
                  :tableColumns="[{prop:'name',label:'人员名称',width: '280'}]"
                  :value.sync="query.userIds"
                  placeholder="请选择业务员"
                  url="/api/dropDown/sysUserList"
                ></table-select>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="部门">
                <treeselect
                  v-model="query.deptIds"
                  :options="deptList"
                  placeholder="请选择部门"
                  style="width: 100%"
                  :normalizer="normalizer"
                  multiple
                  @input="val=>getNoStr(val,'deptList','deptIds')"/>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据类型">
              <el-select v-model="sourceType" collapse-tags multiple class="edit-input" placeholder="请选择单据状态" style="width: 100%;">
                  <el-option
                    v-for="(item,index) in dict.dict_receipt_handover_order_type"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
        </el-col>
        <el-button class="filter-item"  size="mini" type="primary" @click="toQuery">查询</el-button>
        <el-button class="filter-item" plain   size="mini" type="primary" @click="crud.resetQuery" >重置</el-button>

        </el-row>

    </el-form>
    </div>
    <el-form size="small" label-width="85px" >
      <el-row>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="交接日期">
              <el-date-picker
                  v-model="form.busDate"
                  type="date"
                  :disabled="this.$route.params.id !== 'add'"
                  style="width: 100%;"
                  default-value
                  format="yyyy - MM - dd "
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="交接人">
              <zSelect :disabled="this.$route.params.id !== 'add'"
                  :value.sync="handoverUserIds" v-model="handoverUserIds" :showName="handoverUserName" :multiple="true"
                  url="api/dropDown/sysUserList"
                  style="width: 100%"
                />
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="结算人">
              <zSelect :multiple="true" :disabled="this.$route.params.id !== 'add'" :showName="settleUserName" :value.sync="settleUserIds" v-model="settleUserIds"
                  url="api/dropDown/sysUserList"
                  style="width: 100%"
                />
            </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="备注">
              <el-input v-model="remark" clearable placeholder="请输入备注" />
            </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <crudOperation :permission="permission">
      <el-button slot="left" type="primary" @click="save">保存</el-button>
    </crudOperation>
    <el-table ref="table" stripe border v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @row-click="crud.selectRow" @selection-change="crud.selectionChangeHandler" height="700"
    :summary-method="sumRow" show-summary>
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号"/>
        <el-table-column prop="busDate" label="业务日期" />
        <el-table-column prop="sourceCode" label="单据编号" />
        <el-table-column prop="sCustomerName" label="所属二批" />
        <el-table-column prop="pCustomerName" label="所属总店" />
        <el-table-column prop="customerCode" label="客户编码" />
        <el-table-column prop="customerName" label="客户名称" />
        <el-table-column prop="customerAreaName" label="客户区域" />
        <el-table-column prop="customerTypeId" label="客户分类" />
        <el-table-column prop="userName" label="人员" />
        <el-table-column prop="deptName" label="部门" />
        <el-table-column prop="receiveDate" label="应收日期" />
        <el-table-column prop="unCancelAmount" label="未核销金额" />
        <el-table-column prop="remark" label="备注" />
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import { getAreaTree } from '../../../api/erp/basCustomerArea';
import {getCustomerTypeTree} from "@/api/erp/basCustomerType";
import {getDepts} from "@/api/system/dept";
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import pagination from '@crud/Pagination'
import crudOperation from '@crud/CRUD.operation'
import rrOperation from '@crud/RR.operation'
import {saveDetails,saveOrder} from '@/api/erp/receiptHandover'
const defaultCrud = CRUD({
    title: '回单交接',
    url: '/api/slipHandover/drawOrders', sort: '', crudMethod: {  },
    optShow: {
    pass: false,
  },
  })
const defaultForm = {
  busDate:null
 }
export default {
    name: 'ReceiptHandoverAdd',
    components: { pagination,crudOperation,rrOperation,Treeselect},
    mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
    dicts: ['dict_receipt_handover_order_type'],
data(){
    return {
      permission: {
        add: ['admin', 'reportFeePay:add'],
        export: ['admin', 'reportFeePay:export']
      },
      typeList: [],
      areaList: [],
      deptList: [],
      sourceType:[],
      handoverUserName:this.$route.query.handoverUserName,
      settleUserName:this.$route.query.settleUserName,
      handoverUserIds:this.$route.query.handoverUserIds,
      settleUserIds:this.$route.query.settleUserIds,
      remark:this.$route.query.remark,
      form:{
        busDate:this.$route.query.busDate,
      }
    }
},
updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  created() {
    this.getTypeList()
    this.getAreaList()
    this.getdeptList()
  },
  mounted() {
    this.crud.props.searchToggle =false
  },
methods:{
  toQuery(){
    this.query.sourceType= this.sourceType.length?this.sourceType.join(','):''
    this.crud.toQuery()
  },
    sumRow({ columns, data }){
      const sums = []
      for (let i in  columns) {
        if (['feeAmount', 'ownAmount', 'supplierAmount'].includes(columns[i].property)) {
          let selectSum = 0
          this.$refs.table.selection.forEach(item => {
            selectSum += item[columns[i].property]
          })
          sums[i] = <p>{selectSum.toFixed(2)*1}
            <hr/>
            {this.crud.summary[columns[i].property] || 0}</p>
        }
        sums[0] = <p>选中
          <hr/>
          合计</p>
      }
      return sums
    },
    getdeptList() {
        getDepts({status: 1}).then(res => {
      this.deptList = res
    })
    },
    getTypeList() {
      getCustomerTypeTree({page: 0, size: 999}).then(res => {
        this.typeList = res
      })
    },
    getAreaList() {
      getAreaTree().then(res => {
        this.areaList = res
      })
    },
    getNoStr(val, type, prop) {
      let str = "";
      val.forEach((item) => {
        const itemNode = this.getTreeName(this[type], item);
        str = this.getNode(itemNode, str);
      });
      this.query[prop] = str;
    },
    getTreeName(treeList, id) {
      let _this = this;
      for (let i = 0; i < treeList.length; i++) {
        let treeItem = treeList[i];
        if (treeItem.id === id) {
          return treeItem;
        } else {
          if (treeItem.children && treeItem.children.length > 0) {
            let res = _this.getTreeName(treeItem.children, id);
            if (res) {
              return res;
            }
          }
        }
      }
    },
    getNode(node, str) {
      if (node.children) {
        for (let i = 0; i < node.children.length; i++) {
          str = this.getNode(node.children[i], str);
        }
      }
      return (str += node.id + ",");
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    save(){
      this.crud.order.resultList = this.crud.selections
      if(this.crud.selections.length==0){
        this.$message({
          message: '请先勾选！',
          type: 'error'
        })
        return false
      }
      if(this.$route.params.id == 'add'){
        this.crud.order.busDate=this.form.busDate
        this.crud.order.remark=this.remark
        // this.crud.order.handoverPersonList=[]
        const ids = this.handoverUserName?this.handoverUserName.split(','):[]
        const ides = this.settleUserName?this.settleUserName.split(','):[]
        this.crud.order.handoverPersonList = ids.map(item=>{return{userId:item}})
        this.crud.order.settlePersonList = ides.map(item=>{return{userId:item}})
        saveOrder(this.crud.order).then(res=>{
          this.$message({ message: res.msg, type: 'success'})
              this.crud.refresh()
              this.$router.push({path: '/redirect/finance/slipHandoverDetail/' + res.data,query:{}})
        })
      }else{
        this.crud.order.orderId = this.$route.params.id
        saveDetails(this.crud.order).then(res=>{
          this.$message({ message: res.msg, type: 'success' })
            this.crud.refresh()
            this.$router.push({path: '/redirect/finance/receiptHandoverDetail/' + res.data,query:{}})
        })
      }
    }
}
}
</script>

<style scoped>
.flex{
display: flex;
justify-content: center;
}
.flex1{
flex-wrap: wrap;
justify-content: start;
}
</style>
